<?php

// usrPerm
class usrPerm{

    # ==========================================

    // admin, wechat, locin, eduid
    static function cktok($nsp='', $sv=''){
        $kk = 'yskit_' . (empty($nsp) ? 'autok' : $nsp); 
        $token = self::ckget($kk);
        $data = usrJwt::check($token);
        if(empty($data['guid'])){
            $data = ['guid'=>self::guid($nsp)];
            $token = usrJwt::make($data);
            $sv = 1; //self::cksave($kk, $token);
        }
        if($sv){
            self::cksave($kk, $token);
        }
        return $data['guid'];
    }

    static function ckdel($nsp=''){
        $kk = 'yskit_' . (empty($nsp) ? 'autok' : $nsp); 
        self::cksave($kk, '', -1);
    }

    static function guid($nsp=''){ 
        #global $_cbase; 
        $nsp = empty($nsp) ? date('ymd') : $nsp;
        $sid = session_id();
        if(empty($sid)){
            $sid = Basic::envIP() . microtime(1) . Basic::envUA();
        }
        $sid = substr(md5("$sid@$nsp"),6,20);
        //$tex = intval(substr(microtime(1),2)*1000);
        //$tex = Basic::fmtBase32('',$tex,32,8);
        $tex = Basic::kidRand('k',5);
        return "$sid-$tex$nsp";
    }

    // 存cookie
    static function cksave($key, $val='', $life=600){
        global $_cbase; 
        $key = (isset($_cbase['ck']['pre']) ? $_cbase['ck']['pre'] : 'yskit_').$key; 
        $life && $life = $_SERVER["REQUEST_TIME"] + $life; //,  + 72 * 3600
        $path = isset($_cbase['ck']['path']) ? $_cbase['ck']['path'] : '/'; 
        $domain = isset($_cbase['ck']['domain']) ? $_cbase['ck']['domain'] : '';
        $secure = IS_CLI ? '0' : ($_SERVER['SERVER_PORT'] == 443 ? 1 : 0);
        setcookie($key, $val, $life, $path, $domain, $secure);
    }
    // 取cookie
    static function ckget($key){
        global $_cbase; 
        $key = (isset($_cbase['ck']['pre']) ? $_cbase['ck']['pre'] : 'yskit_').$key; 
        return isset($_COOKIE[$key]) ? $_COOKIE[$key] : '';
    }

}

/*  
    // cookie
    static function getCook($nsp=''){
        global $_cbase;
        if(!empty(self::$guid_ck[$nsp])) return self::$guid_ck[$nsp];
        $ua = md5($_cbase['run']['userag'].$nsp);
        $ckey = "{$nsp}_".substr($ua,0,12);
        $cval = comCookie::oget($ckey);
        if(strlen($cval)<32){
            $cval = basKeyid::kidTemp().'-'.basKeyid::kidRand('24',9).'-'.substr($ua,9,9);
            comCookie::oset($ckey,$cval,31622400); //86400*366 = 31 622 400
        }
        self::$guid_ck[$nsp] = $cval;
        return self::$guid_ck[$nsp];
    }
    
    // session_id
    static function getSess($nsp=''){
        return session_id();
    }

    // 获取客户端真实IP(用于guid,session判断)
    static function getUIP($nsp=''){
        return basEnv::userIP();
    }

*/
